package com.quan.system.common.amqp.consumer;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.quan.common.bean.MailBean;
import com.quan.common.constant.CommonConstant;
import com.quan.common.tools.mail.SendMailUtils;
import com.quan.system.entity.SystemEmployee;
import com.quan.system.entity.SystemSettings;
import com.quan.system.service.SystemEmployeeService;
import com.quan.system.service.SystemSettingsService;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

/**
 * 消费端-消息队列监听 
 * 员工年假到期邮件提醒
 * 
 * @author yhaoquan
 *
 */
@Slf4j
@Component
public class ConsumerMessageYearHolidayMailNotify {

	@Autowired
	private SendMailUtils mailUtils;

	@Autowired
	private SystemEmployeeService employeeService;
	
	@Autowired 
    private SystemSettingsService settingsService;
	
	// 配置监听器
	@RabbitListener(bindings = @QueueBinding(
			// 队列(队列的名称,是否持久化)
			value = @Queue(value = CommonConstant.QUEUE_TOPIC_YEAR_HOLIDAY_NOTIFY, durable = "true"),
			// 交换机(交换机的名称,是否持久化,交换机类型)
			exchange = @Exchange(name = CommonConstant.EXCHANGE_TOPIC_MAIL, durable = "true", type = CommonConstant.RABBITMQ_TYPE_TOPIC),
			// 队列Routiny Key
			key = CommonConstant.QUEUE_TOPIC_YEAR_HOLIDAY_NOTIFY))

	@RabbitHandler
	public void process(@Payload Map<String, Object> params, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		log.info("==>【RabbitMQ 消息消费端】开始发送员工年假提醒邮件，队列的名称:{}, 交换机:{}, 路由Key:{}, 消息类型:{}", CommonConstant.QUEUE_TOPIC_YEAR_HOLIDAY_NOTIFY, CommonConstant.EXCHANGE_TOPIC_MAIL, CommonConstant.QUEUE_TOPIC_YEAR_HOLIDAY_NOTIFY, CommonConstant.RABBITMQ_TYPE_TOPIC);

		//获取员工劳动合同到期提醒，邮件收件人
		SystemSettings settings = this.settingsService.loadSettings();	
		
		if (null != params && params.size() > 0) {
			// 根据ID获取当前到期员工信息
			SystemEmployee emp = this.employeeService.getById(params.get("empId").toString());
			
			// 邮件模板参数
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("emp", emp);
			
			MailBean mailBean = new MailBean();
			//mailBean.setTo("liping@whizen.com");
			mailBean.setTo(settings.getEmpTermiEmail());
			mailBean.setSubject("员工年假到期提醒");
			mailBean.setTemplateLocation("mail/YearHoliday_Notify.html");
			mailBean.setTemplateData(map);
			
			this.mailUtils.send(mailBean);
		}

		// ACK签收（delivery_tag，是否批量签收）
		channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);

	}

}
